<?php

namespace app\index\controller\wanlshop;

use app\admin\model\wanlshop\Shop;
use app\common\controller\Wanlshop;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 周边景点
 *
 * @icon fa fa-circle-o
 */
class Scenicspots extends Wanlshop
{

    /**
     * ScenicSpots模型对象
     * @var \app\admin\model\spots\ScenicSpots
     */
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\spots\ScenicSpots;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['shop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('shop')->visible(['shopname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        //设置过滤方法
        $this->request->filter(['trim']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['shop_id'] = $this->shop->id;
                $params['create_time'] = date('Y-m-d H:i:s');

                if(is_array($params['label'])){
                    foreach ($params['label'] as $k =>$v){
                        if(trim($v) == ""){
                            unset( $params['label'][$k]);
                        }
                    }
                    $params['label'] = implode(',',$params['label']) ;
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['shop_id'] !=$this->shop->id) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                if(is_array($params['label'])){
                    foreach ($params['label'] as $k =>$v){
                        if(trim($v) == ""){
                            unset( $params['label'][$k]);
                        }
                    }
                    $params['label'] = implode(',',$params['label']) ;
                }
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $arr =  explode(',',$row['label']);
        while (count($arr) < 2){
            array_push($arr,"");
        }
        $row['labelAll'] = $arr;
        $this->assignconfig("row", $row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 上架或下架
     */
    public function status($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row['status'],['1','2','3'])) {
            $this->error('操作错误，请联系管理员');
        }
        $data['status'] = 1;
        if($row['status'] == 1){
            $data['status'] = 2;
        }

        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $this->model->where('shop_id', '=', $this->shop->id);
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $info = $this->model->get($ids);

        if (!$info) {
            $this->error(__('No Results were found'));
        }
        $shop = Shop::get($info['shop_id']);
        $StatusList = $this->model->getStatusList();

        $info2 = [
            'Shop.shopname'=>$shop ? $shop['shopname'] : '',
            'title'=>$info['title'],
            'Cover_img'=>$info['cover_img'],
            'Label'=>$info['label'],
            'Sketch'=>$info['sketch'],
            'Content'=>$info['content'],
            'Status'=>isset($StatusList[$info['status']]) ? $StatusList[$info['status']] :"",
            'Address'=>$info['address'],
            'Create_time'=>$info['create_time'],
        ];
        if($info['status'] <> '0'){
            $info2['Audit_time']=$info['audit_time'];
        }
        if($info['status'] == '4'){
            $info2['Refuse']=$info['refuse'];
        }

        $this->view->assign("row", $info2);

        return $this->view->fetch();
    }





}
